var HW = require('../../utils/hardware.js'); 
Page({
    data:{
        actionSheetHidden:true,
        deviceList:[],
        linked:false,
        height:138,
        zoneheight:300,
        linked:getApp().globalData.linked,
        linkstate:getApp().globalData.linkstate,
        deviceId:getApp().globalData.deviceId,
        linking:false,
        timer:'',
    },
    onReady:function(e){
        var w = getApp().globalData.screenW;
        var h = getApp().globalData.screenH;
        this.setData({
            height:w*0.48,
            zoneheight:w*0.69
        })
    },
    run:function(){
        wx.navigateTo({url: '../run/run?deviceId='+this.data.deviceId})
    },
    linkHeart:function(){
        var self  =this;
        if(!self.data.linking){
            HW.linkHeart(function(){
                self.setData({
                    linkstate:'搜索中...',
                    linking:true
                })
                self.foundBlue();
            },function(res){
                console.log(res);
                wx.showModal({
                    title: '提示',
                    content: '请在手机-设置-蓝牙 打开蓝牙',
                    showCancel:false
                })
            });
        }else{
            self.closeblue()
            self.setData({
                linking:false
            })
        }
    },
    foundBlue(){
        let self = this;
        let name;
        HW.foundBlue(this,function(devices){
            let name;
            let deviceId;
            if(getApp().globalData.isIOS){ 
                console.log("isiOS")
                deviceId= devices.devices[0].deviceId;
            }else{ 
                deviceId = devices.deviceId
            }
            if(getApp().globalData.isIOS) name= devices.devices[0].name;
            else name = devices.name
            let deviceList = getApp().globalData.deviceList;
            if(!self.isExsit(deviceList,deviceId))deviceList.push(deviceId);   

            self.setData({
                actionSheetHidden:false,
                deviceList:deviceList
            })
        })
    },
    closeblue(){
        HW.closeblue(this);
    },
    cancelAction(){
        this.setData({
            actionSheetHidden:true
        })
        HW.stopSearch();
    },
    selectDevice(e){
        var index = e.target.dataset.index;
        getApp().globalData.linkstate="打卡成功";
        getApp().globalData.linked=true;
        getApp().globalData.deviceId=this.data.deviceList[index];
        this.setData({
            deviceId:this.data.deviceList[index],
            linked:true,
            linkstate:"打开成功",
            actionSheetHidden:true
        })
        HW.stopSearch();
    }, isExsit(list,item){
        for(let i =0;i<list.length;++i){
            if(list[i]===item)return true;
        }
        return false;
    }
})